#!/usr/bin/env bash

shellDir=jenkins/script

echo $'\n'"======= [START] executing run.sh =============== "$'\n'

#####读取配置
file=`readlink -f $0`
WORKSPACE=${file/\/jenkins\/shell\/run.sh/}
export WORKSPACE
cd $WORKSPACE && echo ">> dir change to [$WORKSPACE]"
source jenkins/config

#入参覆盖配置
while getopts ":a:i:s:" opt
do
    case $opt in
    a)
        if [ "config" != "$OPTARG" ] && [ -n "$OPTARG" ] && [ 'null' != "$OPTARG" ]; then
            apps=`echo $OPTARG|cut  -d, -f1- --output-delimiter=$'\n'`
        fi
       ;;
    i)
        if [ "config" != "$OPTARG" ] && [ -n "$OPTARG" ] && [ 'null' != "$OPTARG" ]; then
            deployIps=`echo $OPTARG|cut  -d, -f1- --output-delimiter=$'\n'`
        fi
       ;;
    s)
        if [ -n "$OPTARG" ] && [ 'null' != "$OPTARG" ]; then
            startOnDeployed=$OPTARG
        fi
       ;;
    esac
done

echo " --- params apps[$apps] deployIps[$deployIps] startOnDeployed[$startOnDeployed]"

for i in jenkins/config
do
    if [[ "$i" =~ "=" ]] && ! [[ "$i" =~ "#" ]]; then #包含= 不包含#
        export ${i%%=*} #变量传递给子进程
    fi
done

echo "--------  WORKSPACE is $WORKSPACE --------"
echo "--------  workDir is ${workDir} --------"
echo "-------- deployIps is $deployIps --------"
echo "-------- apps is ${apps} --------"

if [ -z "$deployIps" ] || [ 'null' = "$deployIps" ]; then
    echo "deployIps is empty, check jenkins/config"
    exit
fi


for VAR in $deployConfig ; do


done

for VAR in $deployIps ; do
    eval key='$'$VAR
    echo "---- $VAR is $key --------"
done

############执行sql
echo "#############  run sql ##############"
jenkins/shell/sqlImport.sh

tmpDir=/tmp/jenkins/`basename $WORKSPACE`

if [ ! -d "$tmpDir" ]; then
    mkdir -m 755 "$tmpDir"  && echo "dir[$tmpDir] created"
fi


############# 远程部署（依赖本地部署生成的临时目录）
echo "#############  remote deploy and restart ##############"
for var in $deployIps
do
    if [ -z "$var" ] ; then continue
    fi
    ipTmp=${var#ip_}
    ip=${ipTmp//_/.}

    appsThisNode="$apps"
    #apps变量，无入参则取config配置
    if [ -z "$appsThisNode" ] || [ 'config' = "$appsThisNode" ]; then
        eval appsThisNode='$'$var
    fi
    if [ -z "$appsThisNode" ]; then
        echo "iterm [$var] is not configured in file[config]"
        continue
    fi
    echo " ---->>  collecting apps[$appsThisNode] for [$ip]  <<----"

    #远程备份
    echo "#############  backup[$ip] ##############"
    cat jenkins/config > /tmp/backup$ip.sh
    echo "apps=\"$appsThisNode\"" >> /tmp/backup$ip.sh
    cat jenkins/shell/backupTmpFile.sh >> /tmp/backup$ip.sh
    echo "============>  ssh $server_username@$ip  /usr/bin/bash < /tmp/backup$ip.sh[$appsThisNode]"
    ssh $server_username@$ip /usr/bin/bash < /tmp/backup$ip.sh

    #部署批量脚本
    echo "==========>  scp `find $WORKSPACE/$shellDir -maxdepth 1 -type f` $server_username@$ip:$workDir"
    scp `find $WORKSPACE/$shellDir -maxdepth 1 -type f` $server_username@$ip:$workDir

    echo "#############  deploy[$server_username@$ip] ##############"
    for app in $appsThisNode
    do
        echo "===>  deploying  [$app]"
        if [ -z "$app"  -o 'config' = "$appsThisNode" ] ; then
            echo "app is null, continue"
            continue
        fi
        if [[ "$app" =~ "^etrading" ]] ; then
            echo "app does not start with etrading , continue"
            continue
        fi
        if [ ! -d "$WORKSPACE/jenkins/script/$app" ];then
            echo "==##> directory $WORKSPACE/jenkins/script/$app  not found,skip"
            continue
        fi
        appTmpDir=$tmpDir/$app
        if [ ! -d "$appTmpDir/config" ];then
              mkdir -pm 755 "$appTmpDir/config" && echo "dir[$appTmpDir/config] created"
        fi
        echo "find $WORKSPACE -type f -path \"*/target/*\" -name \"$app-$version.jar\""
        jarFile=`find $WORKSPACE -type f -path "*/target/*" -name "$app-$version.jar"`
        if [ -z "$jarFile" ]
        then
            echo "jarFile of [$app] not found"
            continue
        fi
        targetDir=`dirname $jarFile`
        echo "targetDir[$targetDir]"
        #收集文件-启停脚本
        cp -r $WORKSPACE/jenkins/script/$app/* $appTmpDir
        #收集文件-应用
        if [ -f "$jarFile" ]; then
            echo "cp $jarFile $appTmpDir"
            cp $jarFile $appTmpDir
        else
            echo "jarFile of [$app] not exits"
            continue
        fi
        #收集文件-配置
        cp `find "$targetDir/classes"/ -maxdepth 1  -name "*.properties" ` "$appTmpDir/config"

        #远程部署
        echo "============>   scp -r $appTmpDir $server_username@$ip:$workDir"
        scp -r $appTmpDir $server_username@$ip:$workDir && echo " ---->> APP[$app] deployed to $ip"

        #远程重启
        if [ "$startOnDeployed" = "true" ]; then
            echo "#############  restart[$app] ##############"
            echo '==========> ' "ssh $server_username@$ip \"$workDir/$app/restart.sh\""
            ssh $server_username@$ip "$workDir/$app/restart.sh" && echo "-------> [$app] restarted  <-----------"
        fi
	done

	echo '=================== print running apps =================== '
	echo "-----> ssh $server_username@$ip \"ps -ef |grep $workDir |grep -v grep\""
	ssh $server_username@$ip "ps -ef |grep $workDir |grep -v grep"
	echo '=================== print finished =================== '
done


#发布客户端
echo "#############  update client ##############"
#$WORKSPACE/jenkins/shell/publishClient.sh

#更新备份信息
echo "#############  updateBakInfo ##############"
jenkins/shell/updateBakInfo.sh

echo $'\n'"=======  [END] executing run.sh =============== "$'\n'